<template>
  <div>
    <a-card>
      <a-form ref="filesFormQueryRef" :model="filesFormQueryModel" labelAlign="left" layout="vertical" :style="{ ...coreStyle.marginBottom(18) }">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item :style="{ ...coreStyle.marginBottom(-8) }">
              <a-input-search v-model:value="filesFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="filesFormQuerySubmitting" @search="filesFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="16">
          </a-col>
        </a-row>
      </a-form>
      <a-space>
        <a-button type="dashed" :disabled="filesDetermineDisabled" @click="filesDetermine">
          <CoreIcon icon="grommet-icons:send" :size="14" />
          确定
        </a-button>
        <a-tag color="warning">单选时默认取第一条数据</a-tag>
      </a-space>
      <a-space :style="{ ...coreStyle.floatRight }">
        <a-button type="link" shape="circle" @click="filesListGetDataSet">
          <CoreIcon icon="ci:refresh" :size="22" />
        </a-button>
      </a-space>
      <a-table
        rowKey="id"
        :columns="filesListColumns"
        :data-source="filesListDataSet"
        :loading="filesListLoading"
        :pagination="false"
        bordered
        :row-selection="{ fixed: true, selectedRowKeys: filesListSelectedRowKeys, onChange: filesListRowOnChange }"
        :scroll="{ x: '100%', y: 550 }"
        :style="{ ...coreStyle.marginTop(10) }"
      >
        <template #fileNameTitle>
          <span>文件名称<a-tag color="orange" :style="{ 'line-height': '19px', ...coreStyle.marginLeft(8) }">点击标签查看文件</a-tag></span>
        </template>
        <template #fileUrlTitle>
          <span>文件地址<a-tag color="orange" :style="{ 'line-height': '19px', ...coreStyle.marginLeft(8) }">点击标签复制文件地址</a-tag></span>
        </template>
        <template #fileModuleData="{ text }">
          <span>{{ coreToolStore.getDictDisplayName('fileModuleSearch', text) }}</span>
        </template>
        <template #fileNameData="{ text, record }">
          <a><a-tag color="cyan" :style="{ 'line-height': '19px' }" @click="filesListFileNameClick(record.fileUrl)">{{ text }}</a-tag></a>
        </template>
        <template #fileUrlData="{ text }">
          <!-- <a><a-tag color="purple" :style="{ 'line-height': '19px' } " v-clipboard="text" v-clipboard:success="filesListFileUrlCopySuccess" v-clipboard:error="filesListFileUrlCopyError">{{ text }}</a-tag></a> -->
          <a><a-tag color="purple" :style="{ 'line-height': '19px' } " @click="filesListFileUrlClick(text)">{{ text }}</a-tag></a>
        </template>
        <template #uploadTimesData="{ text }">
          <span>{{ new Date(text).format() }}</span>
        </template>
      </a-table>
      <a-pagination
        v-model:current="filesListDataPage"
        v-model:pageSize="filesListDataRows"
        :total="filesListDataCount"
        show-size-changer
        show-quick-jumper
        :page-size-options="[ ...coreStyle.antdPaginationPageSizeOptions ]"
        :show-total="(total, range) => coreStyle.antdPaginationShowTotal(total, range)"
        :style="{ ...coreStyle.marginTop(10), ...coreStyle.textAlignCenter }"
        @change="filesListPaginationChange"
        @showSizeChange="filesListPaginationShowSizeChange"
        v-if="filesListPaginationVisible"
      >
      </a-pagination>
      <p :style="{ ...coreStyle.marginTop(14), ...coreStyle.marginBottom(6), ...coreStyle.textAlignCenter }" v-if="!filesListPaginationVisible">
        {{ coreStyle.antdPaginationShowTotal(filesListDataCount) }}
      </p>
    </a-card>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import { mapStores } from 'pinia'
import { useCoreToolStore } from '/@/store/modules/cn/core/tool/coreToolStore'
import type { Res } from '/@/tool/Res'
import type { Param } from '/@/tool/Param'

import { useFilesStore } from '/@/store/modules/cn/core/dirs/filesStore'

import type { Files } from '/@/model/cn/core/dirs/eo/Files'
import { toFiles } from '/@/model/cn/core/dirs/eo/Files'

import type { FilesQO } from '/@/model/cn/core/dirs/qo/FilesQO'
import { toFilesQO } from '/@/model/cn/core/dirs/qo/FilesQO'

import type { FilesVO } from '/@/model/cn/core/dirs/vo/FilesVO'
import { toFilesVO } from '/@/model/cn/core/dirs/vo/FilesVO'

@Options({
  name: 'FileSelect',
  props: {
    fileModule: {
      type: String,
      required: true
    },
  },
  emits: [
    'change'
  ],
  components: {
  },
  computed: {
    ...mapStores(useCoreToolStore, useFilesStore),
  },
})
export default class FileSelect extends Vue {

  filesListDataSet: Array<FilesVO> = []

  filesListColumns: Array<object> = [
    {
      title: '文件模块',
      dataIndex: 'fileModule',
      align: 'center',
      slots: { customRender: 'fileModuleData' },
      // ellipsis: true,
      width: 200,
    },
    {
      // title: '文件名称',
      dataIndex: 'fileName',
      align: 'center',
      slots: { title: 'fileNameTitle', customRender: 'fileNameData' },
      ellipsis: true,
      width: 400,
    },
    {
      // title: '文件地址',
      dataIndex: 'fileUrl',
      align: 'center',
      slots: { title: 'fileUrlTitle', customRender: 'fileUrlData' },
      ellipsis: true,
      // width: 200,
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTimes',
      align: 'center',
      slots: { customRender: 'uploadTimesData' },
      // ellipsis: true,
      width: 200,
    },
  ]

  filesListLoading: boolean = false

  filesListSelectedRowKeys: string[] = []

  filesListSelectData: Array<FilesVO> = []

  filesListSelectLength: number = 0

  filesListSelectCurrentRowIndex: number = -1

  filesListSelectCurrentRowData: FilesVO = toFilesVO()

  filesListPaginationVisible: boolean = true

  filesListDataPage: number = 1

  filesListDataRows: number = 10

  filesListDataCount: number = 0

  filesListRowOnChange(selectedRowKeys, selectedRows) {
    this.filesListSelectedRowKeys = [ ...selectedRowKeys ]
    this.filesListSelectData = [ ...selectedRows ]
    this.filesListSelectLength = selectedRows.length
  }

  filesListCustomRow(record, index) {
    return {
      'class': index === this.filesListSelectCurrentRowIndex ? 'ant-table-row-selected' : '',
      onClick: (event) => {
        this.filesListSelectCurrentRowIndex = index
        this.filesListSelectCurrentRowData = { ...record }
        let selectedRowKeys = [ ...this.filesListSelectedRowKeys ]
        let selectedRows = [ ...this.filesListSelectData ]
        if (selectedRowKeys.includes(record.id)) {
          this.filesListRowOnChange([ ...selectedRowKeys.filter(eo => { return eo !== record.id }) ], [ ...selectedRows.filter(eo => { return eo.id !== record.id }) ])
        } else {
          selectedRowKeys.push(record.id)
          selectedRows.push(record)
          this.filesListRowOnChange([ ...new Set(selectedRowKeys) ], [ ...new Set(selectedRows) ])
        }
      },
      onDblclick: (event) => {
        this.filesStore.pkVo(this.$toParam<FilesQO>({ id: this.filesListSelectCurrentRowData.id } as FilesQO)).then((res: Res<FilesVO>) => {
          if (res.succ) {
            this.filesDetailModel = { ...res.data[0] }
            this.filesDetailDrawerVisible = true
          } else {
            this.$message.error(res.msg, 6)
          }
        })
      },
    }
  }

  filesListGetDataSet() {
    this.filesListLoading = true
    this.filesListRowOnChange([], [])
    this.filesListSelectCurrentRowIndex = -1
    this.filesListSelectCurrentRowData = toFilesVO()
    this.filesStore.pagingVo(this.$toParam<FilesQO>({ fileModule: this.fileModule, uploadTimesDesc: 'y' } as FilesQO, this.filesListDataPage, this.filesListDataRows)).then((res: Res<FilesVO>) => {
      if (res.succ) {
        this.filesListPaginationVisible = true
        this.filesListDataSet = [ ...res.data ]
        this.filesListDataCount = res.count
        setTimeout(() => { this.filesListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.filesListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.filesListLoading = false }, 500)
    })
  }

  filesListPaginationChange() {
    this.filesListGetDataSet()
  }

  filesListPaginationShowSizeChange() {
    this.filesListGetDataSet()
  }

  filesListFileNameClick(fileUrl) {
    window.open(this.coreToolStore.getFileFullUrl(fileUrl), '_blank')
  }

  filesListFileUrlClick(value) {
    this.$vclipboard(value).then(e => {
      this.$message.success('文件地址复制成功！', 1)
    }).catch(err => {
      this.$message.error('文件地址复制失败！', 1)
    })
  }

  filesListFileUrlCopySuccess() {
    this.$message.success('文件地址复制成功！', 1)
  }

  filesListFileUrlCopyError() {
    this.$message.error('文件地址复制失败！', 1)
  }

  filesFormQuerySubmitting: boolean = false

  filesFormQueryModel: FilesQO = toFilesQO()

  filesFormQueryReset() {
    if (this.$refs.filesFormQueryRef) {
      this.$refs.filesFormQueryRef.resetFields()
      this.filesFormQueryModel = toFilesQO()
    }
  }

  filesFormQuerySearch() {
    this.filesFormQuerySubmitting = true
    this.filesListLoading = true
    this.filesListRowOnChange([], [])
    this.filesListSelectCurrentRowIndex = -1
    this.filesListSelectCurrentRowData = toFilesVO()
    this.filesStore.queryVo(this.$toParam<FilesQO>(this.$toSearch({ ...this.filesFormQueryModel }))).then((res: Res<FilesVO>) => {
      if (res.succ) {
        this.filesListPaginationVisible = false
        this.filesListDataSet = [ ...res.data ]
        this.filesListDataCount = res.count
        setTimeout(() => { this.filesFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.filesListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.filesFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.filesListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.filesFormQuerySubmitting = false }, 5000)
      setTimeout(() => { this.filesListLoading = false }, 500)
    })
  }

  filesDetermine() {
    let fileUrlList: string[] = []
    this.filesListSelectData.forEach((eo: FilesVO) => {
      fileUrlList.push(eo.fileUrl)
    })
    this.$emit('change', fileUrlList)
  }

  get filesDetermineDisabled() {
    return this.filesListSelectLength > 0 ? false : true
  }

  mounted() {
    this.filesFormQueryModel.fileModule = this.fileModule
    this.filesListGetDataSet()
  }

}
</script>

<style scoped lang="less">

</style>
